package com.mxx.common.data.domain;


import com.mxx.common.exception.UnsupportedTypeException;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.Configurable;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.Type;

import java.io.Serializable;
import java.util.Properties;
import java.util.UUID;

public class UUIDGenerate implements IdentifierGenerator, Configurable {

    @Override
    public void configure(Type type, Properties properties, ServiceRegistry serviceRegistry) throws MappingException {

    }

    @Override
    public Serializable generate(SharedSessionContractImplementor sharedSessionContractImplementor, Object o) throws HibernateException {
        if (JpaThreadContext.hasId()) {
            Serializable id = JpaThreadContext.getUserId();
            JpaThreadContext.removeId();
            if (id instanceof String) {
                try {
                    UUID uuid = UUID.fromString((String) id);
                    return uuid.toString();
                } catch (Exception ex) {
                    throw new UnsupportedTypeException("Current type is " + id.getClass().toString() + ", UUID is required");
                }
            } else {
                throw new UnsupportedTypeException("Current type is " + id.getClass().toString() + ", UUID is required");
            }
        }
        return UUID.randomUUID().toString();
    }
}
